<template>
	<van-form @submit="onSubmit">
		<van-nav-bar title="注册" left-text="" left-arrow @click-left="onClickLeft" />
	  <van-cell-group inset>
	    <van-field
	      v-model="username"
	      name="username"
	      label="用户名"
	      placeholder="用户名"
	      :rules="[
			  { required: true, message: '请填写用户名' },
			]"
	    />
	    <van-field
	      v-model="password"
	      type="password"
	      name="password"
	      label="密码"
	      placeholder="密码"
	      :rules="[{ required: true, message: '请填写密码' }]"
	    />
		<van-field
		  v-model="re_password"
		  type="password"
		  name="re_password2"
		  label="密码"
		  placeholder="再次输入密码密码"
		  :rules="[
			  { required: true, message: '再次输入密码密码' },
			  { validator: checkRePassword, message:'两次输入的密码不一致'}
			]"
		/>
	  </van-cell-group>
	  <div style="margin: 16px;">
	    <van-button round block type="primary" native-type="submit">
	      立即注册
	    </van-button>
	  </div>
	</van-form>
</template>

<script lang="ts" setup>
	import { ref } from 'vue';
	import {checkUsername, createUser} from '@/api/user'
	import 'vant/es/toast/style';
	import { Toast } from 'vant';
	import router from '@/router'
	
	const username = ref('');
	const password = ref('');
	const re_password = ref('');
	
	const onSubmit = (data) => {
      console.log('submit', data);
	  createUser(data)
	  .then(res=>{
		  if(res.code!=0){
			  // 注册失败
			  Toast.fail('注册失败');
			  console.log("注册失败")
		  }else{
			  // 注册成功
			  Toast.success('注册成功');
			  console.log("注册成功")
			  // router.push({
				 //  "name":"login"
			  // })
			  router.push("/login")
		  }
	  })
	  .catch(err=>{
		  // 服务器失败
		  Toast.fail(err);
		  console.log(err)
	  })
    };
	// val => re_password
	const checkRePassword = (val) => {
		// 返回true验证成功，false表示验证失败
		console.log("检查两次密码是否一致")
		if(password.value != re_password.value){
			return false
		}
		return true
	}
	
	const checkUserRepete = (val) => {
		console.log("检查用户名是否被占用")
		
		const params = {
			"username":val
		}
		
		var result = checkUsername(params)
		.then(res => {
			console.log(res)
			if(res.code != 0){
				return `用户名已经被占用，参考用户名....`
			}
			return true
		})
		return  result
	}
	
	// const checkUserRepete = (val) => {
	// 		console.log('检查用户名是否有重复')
	// 		// 返回true验证成功，false表示验证失败
	// 		// 返回字符串表示验证失败，从新定制message
	// 		console.log('请求检查用法接口')
	// 		  let params = {
	// 		    username: "12321"
	// 		  }
	// 		  var result = checkUsername(params)
	// 		  .then(res => {
	// 			  console.log('alal',res.code, res.code != 0)
	// 			  console.log(res)
	// 			  if(res.code != 0){
	// 				    return `${val} 不合法，请重新输入`;
	// 			  }
	// 			  return true
	// 		  })		  
	// 		  .catch(err => {
	// 			  console.log(err)
	// 			  return `服务端错误！`;
	// 		  })
	// 		  return result
	// 	}
	
	// function onSubmit(values){
	// 	console.log('submit', values);
	// }
</script>

<style>
	.side-margin{
		margin: 0px 15px;
	}
	.right{
		text-align: right;
	}
</style>